package com.linan.user.service.impl;

import com.linan.user.service.IverifyCodeService;
import com.linan.util.AjaxResult;
import com.linan.util.HttpUtils;
import com.linan.util.RedisUtils;
import com.linan.util.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;
@Service
public class VerifyCodeServiceImpl implements IverifyCodeService {
    @Override
    public AjaxResult smsRegisterCode(Map<String, String> params) {
        // 获取手机号 并非空校验
        String phone = params.get("phone");
        if(!StringUtils.isNotBlank(phone)){
            return new AjaxResult("请输入正确的手机号");
        }

        //先生成验证码
         String code = StrUtils.getRandomNumber(4);

        //判断redis是否有 并且过了重发时间了没
        String key = "smsCode_register:"+phone;
        String codeFromRedis = RedisUtils.INSTANCE.get(key);
        System.out.println(codeFromRedis);
        if(StringUtils.isNotBlank(codeFromRedis)){
            String time = codeFromRedis.split(":")[1];
            if(System.currentTimeMillis()-Long.valueOf(time)<=300000){
                code = codeFromRedis.split(":")[0];
            }else{
            RedisUtils.INSTANCE.set(key, code+":"+System.currentTimeMillis(),300000);
            }

        }

        final HttpUtils httpUtils = new HttpUtils();
        httpUtils.sendMessage(phone, code);
        //发送验证码
        System.out.println("发送验证码成功"+code);


        return new AjaxResult();
    }
}
